<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace api\doctor\controller;

use think\Db;
use cmf\controller\RestBaseController;
use think\Config;
use think\Cache;

class IndexController extends RestBaseController
{

    public $data;
    public $bizid;
    public $type;
    public $tel;
    public $limit;
    public $doc_id;

    public function __construct(){

        $token =  input('token') ? input('token') : $_SERVER['HTTP_TOKEN'];
        $appid =  input('appid') ? input('appid') : $_SERVER['HTTP_APPID'];
        if(!$token){
            $this->error('缺少:token');
        }
        if(!Cache::get($token)){
            echo json_encode(array('code'=>90001,'msg'=>'token已过期'));die;
        }
        preg_match_all('/\d+/',$token,$arr);
        if(count(@$arr[0]) != 3){
            $this->error('token:有误!');
        }
        if($arr[0][2] == 2){//如果是医生
                $bizid = Db::prefix_close()->table('doctor')
                    ->where(['tel'=>$arr[0][1]])
                    ->value('biz_id');
            $this->type= 2;
        }else{//如果是助手 就只返回他的医生的数据
            $hep = Db::prefix_close()->table('helper')
                    ->where(['tel'=>$arr[0][1]])
                    ->field('biz_id,doc_id')
                    ->find();
            $bizid = $hep['biz_id'];
            $doc_id = $hep['doc_id'];
            $this->type = 3;
        }
        $this->doc_id = isset($doc_id) ? 'c.id = '.$doc_id : '';
        $this->bizid = $bizid;
        $this->data = input();
    }

    /**
     * [doctorMessag description]
     * @return [type] [description]
     */
    public function doctorMessag(){
        if(!isset($this->data['page'])||empty($this->data['page'])||$this->data['page']<=0){
            $this->data['page'] = 1;
        }
        if (!isset($this->data['limit'])||empty($this->data['limit'])) {
            $this->data['limit'] = $this->limit;
        }
        $limit = $this->data['limit'];
        $pages = ($this->data['page']-1)*$limit;
        $data = Db::prefix_close()->table('messagerecord')
            ->alias('a')
            ->join('miniuser b','b.openid=a.openid','left')
            ->join('doctor c','c.id=a.doctorid','left')
            ->field('a.chatid,a.doctorid,a.openid,c.positional_title,a.messagetype,c.name,b.nickname,c.hospital,a.content,b.headimgurl,a.createtime,a.updatetime')
            ->where(['a.bizid'=>$this->bizid])
            ->where($this->doc_id)
            ->group('b.nickname')
            ->limit($pages,$limit)
            ->order('a.createtime desc')
            ->select();
        $newdata = [];
        foreach ($data as $key => $value) {
            $newdata[$key]['doctortype'] = $this->type;
            $newdata[$key]['positional_title'] = $this->getPositionalTitle($value['positional_title']);
            $newdata[$key]['doctorid'] = $value['doctorid'];
            $newdata[$key]['openid'] = $value['openid'];
            $newdata[$key]['servicetype'] = $value['messagetype'];
            $newdata[$key]['servicename'] = $value['messagetype'] == 1 ? '图文问诊':'电话问诊';
            $newdata[$key]['doctorname'] = $value['name'];
            $newdata[$key]['name'] = $value['nickname'];
            $newdata[$key]['hospital'] = $value['hospital'];
            $newdata[$key]['question'] = $value['content'];
            $newdata[$key]['headimg'] = $value['headimgurl'];
            $newdata[$key]['createtime'] = $value['createtime'];
            $newdata[$key]['updatetime'] = $value['updatetime'];
            $newdata[$key]['newMessage'] = 4;
            $newdata[$key]['chatid'] = $value['chatid'];
        }
        $this->success('请求成功！',$newdata);
    }

    /**
     * [messageInfo 消息对话接口]
     * @return [type] [description]
     */
    public function messageInfo(){
        if (!isset($this->data['openid'])||empty($this->data['openid'])) {
            $this->error('缺少:openid');
        }
        if (!isset($this->data['doctorid'])||empty($this->data['doctorid'])) {
            $this->error('缺少:doctorid');
        }
        if(!isset($this->data['page'])||empty($this->data['page'])||$this->data['page']<=0){
            $this->data['page'] = 1;
        }
        if (!isset($this->data['limit'])||empty($this->data['limit'])) {
            $this->data['limit'] = $this->limit;
        }
        $wheres = [];
        if(isset($this->data['maxid']) || !empty($this->data['maxid'])){
            $wheres = 'a.id > '.$this->data['maxid'];
        }
        $limit = $this->data['limit'];
        $pages = ($this->data['page']-1)*$limit;
        $data = Db::prefix_close()->table('messagerecord')
            ->alias('a')
            ->join('miniuser b','b.openid=a.openid','left')
            ->join('doctor c','c.id=a.doctorid','left')
            ->field('c.headimg,c.name,a.id,a.usertype,a.messagetype,b.nickname,a.content,b.headimgurl,a.createtime,a.chatid')
            ->where(['a.openid'=>$this->data['openid'],'a.doctorid'=>$this->data['doctorid']])
            ->where($wheres)
            ->limit($pages,$limit)
            ->order('a.createtime asc')
            ->select();
        $newdata = [];
        foreach ($data as $key => $value) {
            $newdata[$key]['usertype'] = $value['usertype'];
            $newdata[$key]['logo'] = $value['usertype'] == 1 ?  $value['headimgurl'] : $value['headimg'];
            $newdata[$key]['name'] = $value['usertype'] == 1 ?  $value['nickname'] : $value['name'];
            $newdata[$key]['msgtype'] = $value['messagetype'];
            $newdata[$key]['msgcontent'] = $value['content'];
            $newdata[$key]['timestamp'] = strtotime($value['createtime']);
            $newdata[$key]['messageid'] = $value['id'];
            $newdata[$key]['id'] = $value['chatid'];
        }
        $this->success('请求成功！',$newdata);
    }

    /**
     * [messageSend 消息回复]
     * @return [type] [description]
     */
    public function dmessageSend(){
        if (!isset($this->data['openid'])||empty($this->data['openid'])) {
            $this->error('缺少参数[openid]');
        }
        if (!isset($this->data['chatid'])||empty($this->data['chatid'])) {
            $this->error('缺少参数[chatid]');
        }
        if (!isset($this->data['doctorid'])||empty($this->data['doctorid'])) {
            $this->error('缺少参数[doctorid]');
        }
        if (!isset($this->data['msgtype'])||empty($this->data['msgtype'])) {
            $this->error('缺少参数[msgtype]，1文本 2图片');
        }
        if (!isset($this->data['msgcontent'])||empty($this->data['msgcontent'])) {
            $this->error('内容不能为空！[msgcontent]');
        }
        $data['replyopenid'] = $this->data['openid'];
        $data['bizid'] = $this->bizid;
        $data['openid'] = $this->data['openid'];
        $data['doctorid'] = $this->data['doctorid'];
        $data['messagetype'] = $this->data['msgtype'];
        $data['chatid'] = $this->data['chatid'];
        $data['content'] = $this->data['msgcontent'];
        $data['createtime'] = date('Y-m-d H:i:s',time());
        $data['updatetime'] = date('Y-m-d H:i:s',time());
        $data['usertype'] = $this->type; //1医生 2助手 3用户
        $rq = Db::table('messagerecord')->insert($data);
        if($rq){
            $this->success('回复成功!');
        }
        $this->error('回复失败!');

    }
     /**
     * [doctorMessag 电话预约列表]
     * @return [type] [description]
     */
    public function doctorPhoneCall(){
        if (isset($this->data['status'])||!empty($this->data['status'])&&$this->data['status']==2) {
            //$where['a.status'] = 1;//未致电
            if($this->data['status'] == 2){
                $where['a.status'] = 3;
                // $where['a.bookstatus'] = 4;//同意预约
            }else{
                $where = 'a.status != 3';//未致电
            }
        }
        if(!isset($this->data['page'])||empty($this->data['page'])||$this->data['page']<=0){
            $this->data['page'] = 1;
        }
        if (!isset($this->data['limit'])||empty($this->data['limit'])) {
            $this->data['limit'] = $this->limit;
        }
        $limit = $this->data['limit'];
        $pages = ($this->data['page']-1)*$limit;
        $data = Db::prefix_close()->table('chat')
            ->alias('a')
            ->join('miniuser b','b.openid=a.openid','left')
            ->join('doctor c','c.id=a.doctorid','left')
            ->field('a.chatid,c.positional_title,c.name,b.nickname,c.hospital,b.headimgurl,a.booktime,a.updatetime,a.question,a.bookstatus,a.status')
            ->where(['a.bizid'=>$this->bizid])
            ->where($this->doc_id)
            ->where($where)
            ->group('b.nickname')
            ->limit($pages,$limit)
            ->order('a.createtime desc')
            ->select();
        $newdata = [];
        foreach ($data as $key => $value) {
            $newdata[$key]['doctortype'] = $this->type;
            $newdata[$key]['positional_title'] = $this->getPositionalTitle($value['positional_title']);
            $newdata[$key]['chatid'] = $value['chatid'];
            $newdata[$key]['servicetype'] = 2;
            $newdata[$key]['servicename'] = '电话问诊';
            $newdata[$key]['doctorname'] = $value['name'];
            $newdata[$key]['name'] = $value['nickname'];
            $newdata[$key]['hospital'] = $value['hospital'];
            $newdata[$key]['headimg'] = $value['headimgurl'];
            $newdata[$key]['question'] = $value['question'];
            $newdata[$key]['booktime'] = $value['booktime'];
            $newdata[$key]['status'] = $value['status'];
            $newdata[$key]['updatetime'] = $value['updatetime'];
            $newdata[$key]['bookstatus'] = $value['bookstatus'];
            $newdata[$key]['newMessage'] = 4;
        }
        $this->success('请求成功！',$newdata);
    }

    /**
     * [CatInfo 获取电话问诊详情]
     */
    public function catInfo(){
        if (!isset($this->data['chatid'])||empty($this->data['chatid'])) {
            $this->error('缺少:chatid');
        }
        $data = Db::prefix_close()->table('chat')
            ->alias('a')
            ->join('miniuser b','b.openid=a.openid','left')
            ->field('a.virtualtel,b.nickname,a.chatid,a.createtime,a.question,a.bookstatus,a.status,b.nickname,a.booktime,a.rejectreason')
            ->where(['a.chatid'=>$this->data['chatid']])
            ->find();

        $q = json_decode($data['question'],true);
        $newdata['chatid'] = $data['chatid'];//id
        $newdata['info'] = ['name'=>$data['nickname'],'textcontent'=>$q['textcontent'],'tel'=>$data['virtualtel']];
        $newdata['booktime'] = $data['booktime'];//预约致电
        $newdata['status'] = $data['status'];//电话状态
        $newdata['bookstatus'] = $data['bookstatus']; //预约状态
        $newdata['connecttime'] = $data['booktime'];//电话预约
        $newdata['rejectreason'] = $data['rejectreason'];//拒绝理由
        $newdata['textcontent'] = $data['question'];
        $newdata['createtime'] = $data['createtime'];
        $newdata['statusList'] = ['','未预约','预约未响应','拒绝预约','同意预约'];
        if($data){
            $this->success('请求成功！',$newdata);
        }
        $this->error('请求失败！');
    }

    /**
     * [callAppointment 发起预约时间]
     * @return [type] [description]
     */
    public function launchAppointment(){
        if(!isset($this->data['chatid'])||empty($this->data['chatid'])) {
            $this->error('缺少:chatid！');
        }
        if(!isset($this->data['booktime'])||empty($this->data['booktime'])) {
            $this->error('缺少预约时间！');
        }
        $rq = Db::table('chat')->where(['chatid'=>$this->data['chatid']])->update([
            'booktime'=>$this->data['booktime'],
            'bookstatus'=>2,//改为预约未相应！
        ]);
        if($rq){
            $this->success('预约成功！');
        }
        $this->error('发起预约失败！');
    }

    /**
     * [mycenter 医生个人中心]
     * @return [type] [json]
     */
    public function mycenter(){
        $doctor = Db::table('doctor')
            ->where(['id'=>$this->doctorid])
            ->field('id,name,headimg')
            ->find();
        if($doctor){
            $this->success('请求成功!',$doctor);
        }
        $this->error('请求失败!');
    }

    /**
     * [getPositionalTitle 返回医生称号]
     * @param  [type] $positional_title [description]
     * @return [type]                   [description]
     */
    public function getPositionalTitle($positional_title){
        switch ($positional_title) {
            case 1:
                return '医师';
                break;
            case 2:
                return '主治医师';
                break;
            case 3:
                return '副主任医师';
                break;
            case 4:
                return '主任医师';
                break;
            case 5:
                return '副教授';
                break;
            case 6:
                return '教授';
                break;
            default:
                return '无';
                break;
        }
    }


    /**
     * [overInquisition 完成问诊]
     * @return [type] [description]
     */
    public function overInquisition(){
        if (!isset($this->data['chatid'])||empty($this->data['chatid'])) {
            $this->error('缺少参数[chatid]');
        }
        $rq = Db::table('chat')->where(['chatid'=>$this->data['chatid']])->update([
            'status'=>3
        ]);
        if($rq){
            $this->success('完成问诊！');
        }
        $this->error('请求出错！');
    }

    /**
     * [appointment 预约列表接口]
     * @return [type] [description]
     */
    public function appointment(){
        if(!isset($this->data['page'])||empty($this->data['page'])||$this->data['page']<=0){
            $this->data['page'] = 1;
        }
        if (!isset($this->data['limit'])||empty($this->data['limit'])) {
            $this->data['limit'] = $this->limit;
        }

        $limit = $this->data['limit'];
        $pages = ($this->data['page']-1)*$limit;
        $data = Db::prefix_close()->table('miniorder')
            ->alias('a')
            ->join('miniuser b','b.openid=a.openid','left')
            ->join('doctor c','c.id=a.doctorid','left')
            ->field('a.ordertype,a.orderid,a.status,a.orderinfo,c.positional_title,c.name,b.nickname,c.hospital,b.headimgurl,a.updatetime,a.createtime,a.paytime,a.servicetime')
            ->where(['ordertype'=>1])
            ->where($this->doc_id)
            ->where(['a.bizid'=>$this->bizid])
            ->limit($pages,$limit)
            ->order('a.createtime desc')
            ->select();
    //     $data = Db::table('miniorder_copy')->select();
    //     $newdata = [];
    //     foreach ($data as $key => $value) {
    //         $newdata[$key]['bizid'] = $value['bizid'];
    //         $newdata[$key]['orderid'] = $value['orderid'];
    //         $newdata[$key]['openid'] = $value['openid'];
    //         $newdata[$key]['doctorid'] = $value['doctorid'];
    //         $newdata[$key]['transactionid'] = $value['transactionid'];
    //         $newdata[$key]['price'] = $value['price'];
    //         $newdata[$key]['paytime'] = $value['paytime'];
    //         $newdata[$key]['remark'] = $value['remark'];
    //         $newdata[$key]['ordertype'] = $value['ordertype'];
    //         $newdata[$key]['status'] = $value['status'];
    //         $newdata[$key]['poiid'] = $value['poiid'];
    //         $newdata[$key]['orderinfo'] = json_encode(array('name'=>'黄月忠','headerimg'=>'https://qncdn.ocoplus.com/o_1blk6lmil4a01qnd1pi0na21bdu.jpg','poi_name'=>'朱惠医疗门诊部','lng'=>'113.32048','lat'=>'23.10052','address'=>'广东省广州市海珠区艺景路北约新街5号','verify_code'=>mt_rand(400000,999999)),true);
    //         $newdata[$key]['createtime'] = $value['createtime'];
    //         $newdata[$key]['updatetime'] = $value['updatetime'];
    //         $newdata[$key]['ordername'] = $value['ordername'];
    //         $newdata[$key]['itemid'] = $value['itemid'];
    //         $newdata[$key]['itemtype'] = $value['itemtype'];
    //         $newdata[$key]['username'] = $value['username'];
    //         $newdata[$key]['usertel'] = $value['usertel'];
    //         $newdata[$key]['servicetime'] = $value['servicetime'];
    //         // $newdata[$key]['service_time'] = strtotime($value['paytime']);
    //         // $newdata[$key]['service_endtime'] = strtotime($value['servicetime']);
    //         // $newdata[$key]['verify_code'] = mt_rand(400000,999999); 
           
    //     }
        
    // // Db::table('miniorder')->insertAll($newdata);
    //     print_r($newdata);return false; //数据转码
        $newdata = [];
        foreach ($data as $key => $value) {
            $orderinfo = json_decode($value['orderinfo'],true);
            $newdata[$key]['orderid'] = $value['orderid'];
            $newdata[$key]['headimg'] = $value['headimgurl'];
            $newdata[$key]['name'] = $value['nickname'];
            $newdata[$key]['type'] = $value['ordertype'];
            $newdata[$key]['poi_name'] = $orderinfo['poi_name'];
            $newdata[$key]['doctor_name'] = $value['name'];
            $newdata[$key]['timeStr'] = $value['createtime'];
            $newdata[$key]['service_time'] = strtotime($value['paytime']);
            $newdata[$key]['service_endtime'] = strtotime($value['servicetime']);
            $newdata[$key]['verify_code'] = $orderinfo['verify_code'];
        }
        $this->success('请求成功！',$newdata);
    }
    
}